﻿using System;

namespace png2ico
{
    using oueb.Ceen;
    using SanlieHash;
    using SanlieHash.Fast;
    using SanlieHash.GuoMi;
    using tuimg;
    using tuimg.element;

    internal class Png2IcoModule : IHttpModule
    {
        public async Task<bool> HandleAsync(IHttpContext context)
        {
            if (context.Request.Method == "POST")
            {
                var pngbase64 = context.Request.Form["png"];
                var pngbytes = FastEncode.Base64Decode2Bytes(pngbase64);
                using var pngstream = new MemoryStream(pngbytes);
                using var outstream = new MemoryStream();
                var png = new TuimgPng(pngstream);
                var icon = new TuimgIco();
                icon.InsertBmp(png);
                icon.ToStream(outstream);
                context.Response.AddHeader("Content-Disposition", $"attachment; filename=\"{FastGuoMi.GetSM3(pngbase64)}.ico\"");
                await context.Response.WriteAllAsync(outstream, "application/octet-stream");
                return true;
            }
            return false;
        }
    }
}
